import { Input, Popconfirm } from 'antd'
import TypeInput from './type-input'
import {
  useMemo,
  useState,
  forwardRef,
  useImperativeHandle,
  useRef,
} from 'react'
import DynamicTable from '../dynamic-table/index.jsx'
import { v4 as uuidv4 } from 'uuid'

const PopArrayTable = forwardRef(({ type, value, min, max }, ref) => {
  const initRow = () => {
    return {
      key: uuidv4(),
      value: '',
    }
  }

  const [data, setData] = useState(
    value.map((item) => ({ key: uuidv4(), value: item }))
  )
  if (data.length === 0) {
    for (let i = 0; i < 5; i++) {
      data.push(initRow())
    }
  }

  const dataChange = (data) => {
    setData([...data])
  }

  const setValue = (index, value) => {
    const newData = [...data]
    newData[index].value = value
    setData(newData)
  }

  const columns = [
    {
      title: '序号',
      dataIndex: 'index',
      width: 50,
      render: (text, record, index) => {
        return index + 1
      },
    },
    {
      title: '值',
      dataIndex: 'value',
      key: 'key',
      render: (text, record, index) => {
        return (
          <TypeInput
            type={type}
            value={text}
            onChange={(value) => setValue(index, value)}
            min={min}
            max={max}
          />
        )
      },
    },
  ]

  // 方法暴露
  useImperativeHandle(
    ref,
    () => ({
      getData() {
        return [...new Set(data.map((item) => item.value))].filter(
          (item) => item !== ''
        )
      },
    }),
    [data]
  )

  const tableProps = {
    size: 'small',
    scroll: { y: 260 },
  }

  return (
    <DynamicTable
      columns={columns}
      data={data}
      isMove={true}
      onChange={dataChange}
      initRow={initRow}
      tableProps={tableProps}
      actionWidth={140}
    />
  )
})

PopArrayTable.displayName = 'PopArrayTable'

export const ArrayInput = ({ type, value, onChange, min, max }) => {
  const valueList = useMemo(() => (value ? value.split(',') : []), [value])

  const [open, setOpen] = useState(false)
  const handleOpenChange = (newOpen) => {
    setOpen(newOpen)
  }

  const hide = () => {
    setOpen(false)
  }

  const popTableRef = useRef(null)

  const onConfirm = () => {
    onChange(popTableRef.current.getData().join(','))
  }

  const content = (
    <div style={{ width: 350 }}>
      <PopArrayTable
        ref={popTableRef}
        title={null}
        type={type}
        value={valueList}
        min={min}
        max={max}
        onHide={hide}
      />
    </div>
  )

  return (
    <Popconfirm
      icon={null}
      title={content}
      trigger="click"
      open={open}
      onOpenChange={handleOpenChange}
      onCancel={hide}
      onConfirm={onConfirm}
    >
      <Input value={value} readOnly={true} />
    </Popconfirm>
  )
}

export default ArrayInput
